package com.qf.service.impl.blog;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.api.blog.dto.NameDTO;
import com.qf.api.blog.entity.CategoryEntity;
import com.qf.api.blog.service.CategoryService;
import com.qf.core.exception.BaseException;
import com.qf.core.response.ResponseCode;
import com.qf.dao.blog.mapper.CategoryMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


/**
* @author sin
* @description 针对表【t_category(文章分类表)】的数据库操作Service实现
* @createDate 2025-05-23 14:19:29
*/
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryEntity>
    implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public boolean addCategory(NameDTO nameDTO) {
        String categoryName = nameDTO.getName();

        // 先判断该分类是否已经存在
        CategoryEntity category = categoryMapper.selectOne(buildQueryByName("name",categoryName));

        if (category!=null) {
            log.warn("分类名称： {}, 此分类已存在", categoryName);
            throw new BaseException(ResponseCode.CATEGORY_NAME_IS_EXISTED);
        }

        // 构建 CategoryEntity 类
        CategoryEntity insertCategoryEntity = CategoryEntity.builder()
                .name(nameDTO.getName().trim())
                .build();
        // 执行 insert
        return categoryMapper.insert(insertCategoryEntity) > 0;
    }

    @Override
    public boolean updateCategory(Long id, NameDTO nameDTO) {
        String categoryName = nameDTO.getName();

        // 先判断该分类是否已经存在
        CategoryEntity category = categoryMapper.selectOne(buildQueryByName("name",categoryName));

        if (category!=null) {
            log.warn("分类名称： {}, 此分类已存在", categoryName);
            throw new BaseException(ResponseCode.CATEGORY_NAME_IS_EXISTED);
        }
        CategoryEntity updateCategory = CategoryEntity.builder()
                .id(id)
                .name(categoryName.trim())
                .build();
        return categoryMapper.updateById(updateCategory) > 0;
    }

    private QueryWrapper<CategoryEntity> buildQueryByName(String column,String categoryName) {
        return new QueryWrapper<CategoryEntity>().eq(column, categoryName);
    }

}




